<template>
  <div class="menu-management">
    <el-card>
      <div class="card-header">
        <span>菜单管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加菜单
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <el-form :inline="true" class="search-form" :model="searchForm" @submit.native.prevent>
        <el-form-item label="菜单名称">
          <el-input v-model="searchForm.menuName" placeholder="请输入菜单名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="父菜单">
          <el-select v-model="searchForm.parentId" placeholder="请选择父菜单" clearable>
            <el-option label="顶级菜单" value="0"></el-option>
            <el-option v-for="menu in parentMenuList" :key="menu.id" :label="menu.menuName" :value="menu.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="menuList" style="width: 100%" v-loading="loading">
        <el-table-column prop="menuName" label="菜单名称" min-width="150"></el-table-column>
        <el-table-column prop="parentMenuName" label="父菜单" min-width="150"></el-table-column>
        <el-table-column prop="path" label="菜单路径" min-width="150"></el-table-column>
        <el-table-column prop="component" label="组件路径" min-width="200"></el-table-column>
        <el-table-column prop="icon" label="图标" width="80">
          <template slot-scope="scope">
            <i v-if="scope.row.icon" :class="scope.row.icon"></i>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序号" width="100"></el-table-column>
        <el-table-column prop="isVisible" label="是否可见" width="100">
          <template slot-scope="scope">
            <el-switch 
              v-model="scope.row.isVisible" 
              active-color="#13ce66" 
              inactive-color="#ff4949"
              @change="handleVisibleChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="isEnabled" label="是否启用" width="100">
          <template slot-scope="scope">
            <el-switch 
              v-model="scope.row.isEnabled" 
              active-color="#13ce66" 
              inactive-color="#ff4949"
              @change="handleEnabledChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="el-dropdown-link">
                <i class="el-icon-setting"></i>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{ type: 'edit', data: scope.row }">编辑</el-dropdown-item>
                <el-dropdown-item :command="{ type: 'delete', data: scope.row }" type="danger">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MenuList',
  data() {
    return {
      menuList: [],
      parentMenuList: [],
      loading: false,
      searchForm: {
        menuName: '',
        parentId: ''
      }
    };
  },
  mounted() {
    console.log('MenuList组件已挂载，准备加载菜单数据');
    this.loadMenus();
    this.loadParentMenus();
  },
  methods: {
    loadMenus() {
      console.log('开始加载菜单数据');
      this.loading = true;
      
      console.log('准备调用menuApi.getAll:', this.$api.menuApi);
      if (!this.$api || !this.$api.menuApi) {
        console.error('API对象或menuApi不存在');
        this.loading = false;
        return;
      }
      
      this.$api.menuApi.getAll()
        .then(data => {
          console.log('获取菜单数据成功:', data);
          // http.js已经处理了响应格式，这里直接获取数据
          let menuData = data && data.data || [];
          
          // 获取父菜单名称
          menuData = menuData.map(menu => {
            const parentMenu = this.parentMenuList.find(p => p.id === menu.parentId);
            return {
                ...menu,
                parentMenuName: parentMenu ? parentMenu.menuName : '顶级菜单'
              };
            });
            
            // 应用搜索条件
            if (this.searchForm.menuName) {
              menuData = menuData.filter(item => item.menuName.includes(this.searchForm.menuName));
            }
            if (this.searchForm.parentId !== '') {
              menuData = menuData.filter(item => item.parentId === this.searchForm.parentId);
            }
            
            this.menuList = menuData;
            this.loading = false;
        })
        .catch(error => {
          console.error('获取菜单列表失败:', error);
          this.$message.error('获取菜单列表失败');
          this.loading = false;
        });
    },
    
    loadParentMenus() {
      this.$api.menuApi.getAll()
        .then(data => {
          // http.js已经处理了响应格式，这里直接获取数据
          this.parentMenuList = data && data.data || [];
        })
        .catch(error => {
          console.error('获取父菜单列表失败:', error);
        });
    },
    
    handleSearch() {
      this.loadMenus();
    },
    
    handleReset() {
      this.searchForm = {
        menuName: '',
        parentId: ''
      };
      this.loadMenus();
    },
    
    handleAdd() {
      this.$router.push('/menu/add');
    },
    
    handleEdit(row) {
      this.$router.push({
        path: '/menu/edit',
        query: { id: row.id }
      });
    },
    
    handleDelete(row) {
      this.$confirm('确定要删除该菜单吗？删除后将同时删除其下的所有子菜单。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
            this.$api.menuApi.delete(row.id)
              .then(data => {
                this.$message.success('删除成功');
                this.loadMenus();
                this.loadParentMenus(); // 重新加载父菜单列表
              })
          .catch(error => {
            this.$message.error('删除失败: ' + error.message);
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    handleVisibleChange(row) {
      // 更新是否可见状态
      this.$api.menuApi.update(row.id, row)
        .then(data => {
          // http.js已经处理了响应格式，不需要额外判断
          // 如果请求失败，catch部分会处理
        })
        .catch(error => {
          // 如果请求失败，恢复原来的状态
          row.isVisible = !row.isVisible;
          this.$message.error('更新状态失败: ' + error.message);
        });
    },
    
    handleEnabledChange(row) {
      // 更新是否启用状态
      this.$api.menuApi.update(row.id, row)
        .then(data => {
          // http.js已经处理了响应格式，不需要额外判断
          // 如果请求失败，catch部分会处理
        })
        .catch(error => {
          // 如果请求失败，恢复原来的状态
          row.isEnabled = !row.isEnabled;
          this.$message.error('更新状态失败: ' + error.message);
        });
    },
    
    handleCommand(command) {
      if (command.type === 'edit') {
        this.handleEdit(command.data);
      } else if (command.type === 'delete') {
        this.handleDelete(command.data);
      }
    },
    
    handleRefresh() {
      this.loadMenus();
    }
  }
};
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
}

.search-form {
  margin-bottom: 20px;
}
</style>